// 校验用户输入有效性；监测旧密码是否正确；后端修改密码
import Toast from '@vant/weapp/toast/toast';
import verifyToken from "../../utils/verifyToken"
import {changePassword} from "../../api/account"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    phoneNumber:"",
    oldPwd:"rugvty12",
    newPwd:"rugvty485321",
    confirmNewPwd:"rugvty485321",
    oldPwdTips:"", // 旧密码不能为空
    newPwdTips:"",  // 新密码不能与旧密码一致
    confirmNewPwdTips:"" // 新密码应与确认密码一致
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad (options) {
    let ret = await verifyToken()
    // console.log(ret);
    let {phoneNumber} = ret

    this.setData({
      phoneNumber
    })
  },

  // 提交新密码
  submit(){
    console.log(111)
  },

  // 提示初始化
  tipsInit(){
    this.setData({
      oldPwdTips:"",
      newPwdTips:"",
      confirmNewPwdTips:""
    })
  },
  // 检验用户输入有效性
  inputChange(){
    let {oldPwd,newPwd,confirmNewPwd} = this.data
    let isSafe = /^.*(?=.{8,})(?=.*\d)(?=.*[a-zA-Z]).*$/.test(newPwd)
    // console.log(isSafe)
    // console.log(newPwd !== confirmNewPwd);

    if((newPwd.length != 0 || confirmNewPwd.length != 0) && oldPwd.length == 0){
      this.setData({
        oldPwdTips:"旧密码不能为空"
      })
    }else{
      this.setData({
        oldPwdTips:""
      })
    }

    if(oldPwd === newPwd){
      this.setData({
        newPwdTips:"新密码不能与旧密码一致"
      })
    }else if(!(/^.*(?=.{8,})(?=.*\d)(?=.*[a-zA-Z]).*$/.test(newPwd))){
      
      this.setData({
        newPwdTips:"密码组合要求至少8位，且包含一位数字和一位字母"
      })
    }else{
      this.setData({
        newPwdTips:""
      })
    }
    
    if(newPwd !== confirmNewPwd){
      this.setData({
        confirmNewPwdTips:"确认密码与新密码不一致"
      })
    }else{
      this.setData({
        confirmNewPwdTips:""
      })
    }

  },

  // 提交
  async submit(){
    let {oldPwd,newPwd,confirmNewPwd,oldPwdTips,newPwdTips,confirmNewPwdTips,phoneNumber} = this.data
    if(oldPwd.length != 0 && newPwd.length != 0 && confirmNewPwd.length != 0
      && oldPwdTips.length == 0 && newPwdTips.length == 0 && confirmNewPwdTips.length == 0){
        let ret = await changePassword({
          phoneNumber,
          oldPwd,
          newPwd
        })

        if(ret.code === 200){
          Toast({
            type:"success",
            message:ret.message
          })
        }else{
          Toast({
            type:"fail",
            message:ret.message
          })
        }
    }else{
      Toast({
        type:"fail",
        message:"输入有误，请修改后再提交"
      })
    }
  }
})